package com.sysystem.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sysystem.common.Constant;
import com.sysystem.common.DevidePage;
import com.sysystem.enums.BaseRetCode;
import com.sysystem.model.Train;
import com.sysystem.service.ITrainService;
import com.sysystem.vo.BaseResponseVO;

@RestController
public class TrainController extends BaseController {
    
    private static Logger logger = LoggerFactory.getLogger(TrainController.class);

    @Autowired
    private ITrainService trainService;
    
    @RequestMapping(value = "/train", method = RequestMethod.POST)
    public BaseResponseVO train(@RequestParam(value="wechat_cd",required=false) String wechat_cd,
    							@RequestParam(value="train_kb",required=false) String train_kb,
    							@RequestParam(value="pageNo",required=false) String pageNo) {
        try {
            logger.info("---TrainController START---");
            
            if (StringUtils.isEmpty(train_kb)) {
            	train_kb = Constant.TRAIN_KB_ONE;
            }
            
            int currentPage = 1;// 当前页是第一页
            if (!StringUtils.isEmpty(pageNo)) {
    			currentPage = Integer.parseInt(pageNo);
    		}
            
            // 总记录条数 
            int recordCount = trainService.selectAllDataCount(train_kb);
    		DevidePage pUtil = new DevidePage(Constant.PAGE_SIZE, recordCount, currentPage);
    		int start = pUtil.getFromIndex();
    		int end = pUtil.getToIndex();
    		
    		//总页数
    		int pageCount = pUtil.getPageCount();
    		if (currentPage > pageCount) {
    			// 没有更多的记录
    			return this.buildRespone(BaseRetCode.CODE_ERROR_NO_MOREDATA);
    		}

    		List<Train> trainList = trainService.selectAllData(wechat_cd, train_kb, start, end);
            
            logger.info("---TrainController END");
            
            BaseResponseVO resData = this.buildResultDataRespone(trainList);
            
            return resData;
        } catch(Exception e) {
            e.printStackTrace();
            return this.buildRespone(BaseRetCode.CODE_ERROR_SYS);
        }
    }
}
